package com.hehui.immersive;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Activity界面属性设置工具类。
 *
 * @author hehui
 *         ~
 * @date 2016/11/2
 */
public class ActivityPropertiesUtil {

    private static final String TAG = "ActivityPropertiesUtil";

    /**
     * 初始化Windows属性。
     *
     * @param activity
     * @param needCheckToolbar
     */
    public static void initWindowsProperties(Activity activity, boolean needCheckToolbar) {
        if (!needCheckToolbar) {
            return;
        }

        try {
            if (activity == null || activity.isFinishing()) {
                return;
            }

            Window window = activity.getWindow();
            if (window == null) {
                return;
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                // 把状态栏直接隐藏了
                window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                        WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }


            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if (isNullOrEmpty(getBaseBandVersion())) {
                    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                }

                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            }
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
    }

    /**
     * 初始化Activity属性。
     *
     * @param activity
     * @param needCheckToolbar
     */
    public static void initActivityProperties(Activity activity, boolean needCheckToolbar) {
        if (!needCheckToolbar) {
            return;
        }

        if (activity == null || activity.isFinishing()) {
            return;
        }

        CoordinatorLayout coordinatorLayout = (CoordinatorLayout) activity.findViewById(R.id.common_coordinator_layout);
        if (coordinatorLayout == null) {
            throw new IllegalArgumentException("coordinatorLayout is null.");
        }
        AppBarLayout appBarLayout = (AppBarLayout) activity.findViewById(R.id.common_appbar_layout);
        if (appBarLayout == null) {
            throw new IllegalArgumentException("appBarLayout is null.");
        }
        Toolbar toolBar = (Toolbar) activity.findViewById(R.id.common_toolbar);
        if (toolBar == null) {
            throw new IllegalArgumentException("toolBar is null.");
        }

        try {
            int appBarHeight = appBarLayout.getHeight();
            int statusBarHeight = getStatusBarHeight(activity.getApplicationContext());
            if (statusBarHeight == 0) {
                statusBarHeight = getStatusBarHeightReflect(activity.getApplicationContext());
            }
            int toolBarHeight = toolBar.getHeight();

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
                int visibleCount = visibleCount(appBarLayout);
                if (visibleCount == 1) {
                    AppBarLayout.LayoutParams toolBarParams = (AppBarLayout.LayoutParams) toolBar
                            .getLayoutParams();

                    int offset = (int) Math.ceil((double) (appBarHeight + statusBarHeight - toolBarHeight) / 2);
                    toolBarParams.topMargin = offset;

                    toolBar.setLayoutParams(toolBarParams);
                } else if (visibleCount > 1) {
                    AppBarLayout.LayoutParams toolBarParams = (AppBarLayout.LayoutParams) toolBar
                            .getLayoutParams();
                    CoordinatorLayout.LayoutParams appBarParams = (CoordinatorLayout.LayoutParams) appBarLayout
                            .getLayoutParams();
                    FrameLayout.LayoutParams coordinatorParams = (FrameLayout.LayoutParams) coordinatorLayout
                            .getLayoutParams();

                    int offset = (int) Math.ceil((double) (appBarHeight + statusBarHeight - toolBarHeight) / 2);
                    toolBarParams.topMargin = offset;

                    toolBar.setLayoutParams(toolBarParams);

                    appBarParams.topMargin = -appBarLayout.getTotalScrollRange() * 2 + statusBarHeight;
                }
            }
            // 4.4系统以下
            else {
                AppBarLayout.LayoutParams toolBarParams = (AppBarLayout.LayoutParams) toolBar
                        .getLayoutParams();
                CoordinatorLayout.LayoutParams appBarParams = (CoordinatorLayout.LayoutParams) appBarLayout
                        .getLayoutParams();

                int offset = (int) Math.ceil((double) (appBarHeight + statusBarHeight - toolBarHeight) / 2);
                toolBarParams.topMargin = offset;
                appBarParams.topMargin = -offset;

                toolBar.setLayoutParams(toolBarParams);
                appBarLayout.setLayoutParams(appBarParams);

                FrameLayout.LayoutParams coordinatorParams = (FrameLayout.LayoutParams) coordinatorLayout
                        .getLayoutParams();
                coordinatorParams.bottomMargin = -offset;
                coordinatorLayout.setLayoutParams(coordinatorParams);
            }
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier(
                "status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public static int visibleCount(ViewGroup view) {
        int result = 0;

        int childCount = view.getChildCount();
        View tempView = null;
        for (int i = 0; i < childCount; i++) {
            tempView = view.getChildAt(i);
            if (tempView == null) {
                continue;
            }

            if (tempView.getVisibility() == View.VISIBLE) {
                result += 1;
            }
        }

        return result;
    }

    /**
     * 获取通知栏（状态栏）的高度
     *
     * @return statusBarHeight
     */
    public static int getStatusBarHeightReflect(Context context) {
        Class<?> clazz;
        Object object;
        Field field;
        int x;
        int statusBarHeight = 0;

        try {
            clazz = Class.forName("com.android.internal.R$dimen");
            object = clazz.newInstance();
            field = clazz.getField("status_bar_height");
            x = Integer.parseInt(field.get(object).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
        return statusBarHeight;
    }

    /**
     * 字符串是否为{@code null}或者空字符串。
     *
     * @param s
     * @return
     */
    public static boolean isNullOrEmpty(String s) {
        return s == null || s.length() == 0;
    }

    /**
     * 获取基带版本信息。
     *
     * @return
     */
    public static String getBaseBandVersion() {
        String version = "";
        try {
            Class cl = Class.forName("android.os.SystemProperties");
            Object invoker = cl.newInstance();
            Method m = cl.getMethod("get", new Class[]{String.class, String.class});
            Object result = m.invoke(invoker, new Object[]{"gsm.version.baseband", ""});
            version = String.valueOf(result);
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }

        return version;
    }
}